//
//  DZHomeViewController.m
//  好奇心日报
//
//  Created by 董筱泽 on 2017/11/25.
//  Copyright © 2017年 董筱泽. All rights reserved.
//
#import "DZHomeViewController.h"

//工具类
#import "JFConfigFile.h"
#import "JFLoopView.h"
#import "YYFPSLabel.h"

//第三方开源框架
#import <Masonry.h>
#import <MJRefresh.h>
#import "MJExtension.h"

//
#import "MBProgressHUD+JFProgressHUD.h"
#import "DZReaderViewController.h"
#import "DZHomeNewsDataManager.h"
#import "DZHomeNewsTableViewCell.h"



//新闻数据模型相关
#import "DZResponseMedel.h"
#import "DZNewsCellLayout.h"
//#import "JFQDaily-Swift.h"

@interface DZHomeViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSString *_last_key;        // 上拉加载请求数据时需要拼接到URL中的last_key
    NSString *_has_more;        // 是否还有未加载的文章（0：没有 1：有）
    CGFloat _contentOffset_Y;   // homeNewsTableView滑动后Y轴偏移量
    NSInteger _row;
    BOOL _isRuning;             // 定时器是否在运行
    BOOL _isBeyondBorder;       // 轮播view是否超出显示区域
}

@property (nonatomic, strong) UITableView *homeNewsTableView;
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *refreshFooter;
@property (nonatomic, strong) DZHomeNewsTableViewCell *cell;

@property (nonatomic, strong) JFLoopView *loopView;
@property (nonatomic, strong) YYFPSLabel *fpsLabel;

@property (nonatomic, strong) DZHomeNewsDataManager *manager;
@property (nonatomic, strong) DZResponseModel *response;
@property (nonatomic, strong) NSArray *feedsArray;
@property (nonatomic, strong) NSArray *bannersArray;
@property (nonatomic, strong) NSArray *imageArray;
/** 主要内容数组*/
@property (nonatomic, strong) NSMutableArray *contentMutableArray;
@property (nonatomic, strong) NSMutableArray <DZNewsCellLayout *> *layouts;
    
    @end

@implementation DZHomeViewController
    
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    
    [self.view addSubview:self.homeNewsTableView];
    
    
    self.contentMutableArray = [[NSMutableArray alloc] init];
    self.layouts = [[NSMutableArray alloc] init];
    self.imageArray = [[NSArray alloc] init];
    
    //请求数据
    [self requestDataWith:@"0"];
    
    //设置下拉刷新
    self.refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshData];
    }];
    self.refreshHeader.lastUpdatedTimeLabel.hidden = YES;
    self.refreshHeader.stateLabel.hidden = YES;
    self.homeNewsTableView.mj_header = self.refreshHeader;
    
    //设置上拉加载
    self.refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadData]; //已在scrollViewDidScroll里提供了加载数据
    }];
    [self.refreshFooter setTitle:@"加载更多 ..." forState:MJRefreshStateRefreshing];
    [self.refreshFooter setTitle:@"没有更多内容了" forState:MJRefreshStateNoMoreData];
    self.homeNewsTableView.mj_footer = self.refreshFooter;
    
    //FPS Label
    _fpsLabel = [[YYFPSLabel alloc] initWithFrame:CGRectMake(20, 44, 100, 30)];
    [_fpsLabel sizeToFit];
    [self.view addSubview:_fpsLabel];
}
    
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    //self.automaticallyAdjustsScrollViewInsets = NO;
    if (!_isBeyondBorder) {
        [self.loopView startTimer];
    }
}
    
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (_isRuning && !_isBeyondBorder) {
        [self.loopView stopTimer];
        _isRuning = NO;
    }
}
    
    /// 下拉刷新数据
- (void)refreshData {
    //下拉刷新时清空数据
    [_layouts removeAllObjects];
    [self requestDataWith:@"0"];
}

    /// 上拉加载数据
- (void)loadData {
    //判断是否还有更多数据
    if ([_has_more isEqualToString:@"1"]) {
        [self requestDataWith:_last_key];
    }else if ([_has_more isEqualToString:@"0"]) {
        [self.refreshFooter setState:MJRefreshStateNoMoreData];
    }
}
    

    
#pragma mark --- 数据管理器
- (DZHomeNewsDataManager *)manager {
    if (!_manager) {
        _manager = [[DZHomeNewsDataManager alloc] init];
    }
    return _manager;
}
    
- (void)requestDataWith:(NSString *)key {
    [self.manager requestHomeNewsDataWithLastKey:key
                                          result:^(id data) {
    self.response = [DZResponseModel mj_objectWithKeyValues:data];
    _last_key = self.response.last_key;
    _has_more = self.response.has_more;
                                              
//使用MJExtension讲josn数据转成数组
    self.bannersArray = [DZFeedsModel mj_objectArrayWithKeyValuesArray:[data valueForKey:@"banners"]];
                                              
//使用MJExtension讲josn数据转成数组
    self.feedsArray = [DZFeedsModel mj_objectArrayWithKeyValuesArray:[data valueForKey:@"feeds"]];
                                              
    for (DZFeedsModel *feed in self.feedsArray) {
    DZNewsCellLayout *layout = [[DZNewsCellLayout alloc] initWithModel:feed style:[feed.type integerValue]];
                                                  
    [self.layouts addObject:layout];
                                                  
//停止刷新
    [self.refreshHeader endRefreshing];
    [self.refreshFooter endRefreshing];

    [self.homeNewsTableView reloadData];
        }
    }
    failure:^(id message) {
    [MBProgressHUD promptHudWithShowHUDAddedTo:self.view message:@"网络异常！"];
    }];
}
    

    
#pragma mark --- JFHomeNewsTableView（首页根view）
- (UITableView *)homeNewsTableView {
    if (!_homeNewsTableView) {
        _homeNewsTableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
        _homeNewsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _homeNewsTableView.delegate = self;
        _homeNewsTableView.dataSource = self;
        _homeNewsTableView.tableHeaderView = self.loopView;
    }
    return _homeNewsTableView;
}
    

    
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _layouts.count;
    
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return ((DZNewsCellLayout *)_layouts[indexPath.row]).height;
}
    
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"newsCell";
    self.cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!_cell) {
        _cell = [[DZHomeNewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    [_cell setLayout:_layouts[indexPath.row]];
    return _cell;
}
    
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DZNewsCellLayout *layout = _layouts[indexPath.row];
    if (![layout.model.type isEqualToString:@"0"]) {
        [self pushToJFReaderViewControllerWithNewsUrl:layout.model.post.appview];
    }else {
        [MBProgressHUD promptHudWithShowHUDAddedTo:self.view message:@"抱歉，未抓取到相关链接！"];
    }
}
    
/// push到JFReaderViewController
- (void)pushToJFReaderViewControllerWithNewsUrl:(NSString *)newsUrl {
    DZReaderViewController *readerVC = [[DZReaderViewController alloc] init];
    readerVC.newsUrl = newsUrl;
    [self.navigationController pushViewController:readerVC animated:YES];
}
    
   
    

@end

